package com.wptai.disconf.client.core;

import com.baidu.disconf.client.DisconfMgrBean;
import com.baidu.disconf.client.DisconfMgrBeanSecond;
import com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean;
import com.wptai.disconf.client.config.ReloadingPropertyPlaceholderConfigurer;
import com.wptai.disconf.client.data.DisconfData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import java.util.Properties;

@Slf4j
public class DisConfig implements EnvironmentAware {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public DisConfigPreProcessing getDisConf() {
        DisConfigPreProcessing bean = new DisConfigPreProcessing();
        return bean;
    }

    @Bean(destroyMethod = "destroy")
    public DisconfMgrBean disconfMgrBean(DisConfigPreProcessing disConfigPreProcessing) {
        DisconfMgrBean bean = new DisconfMgrBean();
        bean.setScanPackage(disConfigPreProcessing.getDisconfData().getScan());
        return bean;
    }


    @Bean(initMethod = "init", destroyMethod = "destroy")
    public DisconfMgrBeanSecond disconfMgrBeanSecond() {
        DisconfMgrBeanSecond bean = new DisconfMgrBeanSecond();
        return bean;
    }

    @Bean(destroyMethod = "destroy")
    public ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean(DisConfigPreProcessing disConfigPreProcessing) {
        ReloadablePropertiesFactoryBean bean = new ReloadablePropertiesFactoryBean();
        bean.setLocations(disConfigPreProcessing.getDisconfData().getAutoReloadFileList());
        return bean;
    }

    @Bean(destroyMethod = "destroy")
    public ReloadingPropertyPlaceholderConfigurer reloadingPropertyPlaceholderConfigurer(ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean) throws Exception {
        ReloadingPropertyPlaceholderConfigurer bean = new ReloadingPropertyPlaceholderConfigurer();
        Properties[] propertiesArray = {reloadablePropertiesFactoryBean.getObject()};
        bean.setPropertiesArray(propertiesArray);
        return bean;
    }

    @Override
    public void setEnvironment(Environment environment) {
        DisconfData.paramList.forEach(p  -> {
            String envParam = environment.getProperty(p);
            if(envParam != null ){
                log.info("environment param:" +envParam);
                System.setProperty(p, envParam);
            }
        });
    }
}
